<?php

namespace App\Repository;

use App\Models\UserRecommend;

class UserRecommendRepository extends BaseRepository
{
    /**
     * 新增用户推荐记录
     * @param $loadData
     * @return bool|UserRecommend|null
     */
    public function createUserRecommend($loadData)
    {
        return UserRecommend::getModel($loadData['user_id'])->create($loadData);
    }

    /**
     * 修改【用户推荐】记录
     * @param UserRecommend $userRecommend
     * @param $loadData
     * @return bool|int
     */
    public function updateUserRecommend(UserRecommend $userRecommend, $loadData)
    {
        return $userRecommend->update($loadData);
    }

    /**
     * 通过主体ID取消推荐
     * @param $userId
     * @param $targetId
     * @return bool|UserRecommend|null
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public function cancelByTargetId($userId, $targetId)
    {
        $model = $this->getUserRecommendByTargetId($userId, $targetId);
        if (!$model) {
            return false;
        }

        $model->delete();

        return $model;
    }

    /**
     * 通过用户ID、主体ID获取用户推荐记录
     * @param $userId
     * @param $targetId
     * @return \Illuminate\Database\Eloquent\Builder|UserRecommend|object|null
     */
    public function getUserRecommendByTargetId($userId, $targetId)
    {
        return UserRecommend::getInstance($userId)
            ->where('user_id', $userId)
            ->where('target_id', $targetId)
            ->first();
    }
}
